package com.huarui.saleReturn.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.code.dao.ICodeGenericDao;
import com.huarui.code.model.CodeGeneric;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.inventory.dao.IInventoryDao;
import com.huarui.inventory.model.Inventory;
import com.huarui.partner.dao.IPartnerDao;
import com.huarui.partner.model.Partner;
import com.huarui.quotation.service.QuotationService;
import com.huarui.receivable.dao.IReceivableDao;
import com.huarui.receivable.model.Receivable;
import com.huarui.sale.dao.IExpressDao;
import com.huarui.sale.dao.IExpressItemDao;
import com.huarui.sale.dao.ISaleDao;
import com.huarui.sale.dao.ISaleItemDao;
import com.huarui.sale.model.Express;
import com.huarui.sale.model.Sale;
import com.huarui.sale.util.SaleConstantEnum;
import com.huarui.saleReturn.button.SaleReturnButtonService;
import com.huarui.saleReturn.dao.ISaleReturnDao;
import com.huarui.saleReturn.dao.ISaleReturnItemDao;
import com.huarui.saleReturn.model.SaleReturn;
import com.huarui.saleReturn.model.SaleReturnItem;
import com.huarui.saleReturn.util.ConstantParamEnum;
import com.huarui.user.dao.IUserDao;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.model.User;
import com.huarui.user.security.UserHolder;

public class SaleReturnService extends BaseService {
   
	private ISaleReturnDao getDao(){
		return (ISaleReturnDao) dao;
	}
	
	private ISaleDao saleDao;
	
	private ISaleItemDao saleItemDao;
	
	private IExpressDao expressDao;
	
	private IExpressItemDao expressItemDao;
	
	private ICodeGenericDao codeGenericDao;
	
	private IUserDao userDao;
	
	private ISaleReturnItemDao saleReturnItemDao;
	
	private SaleReturnButtonService saleReturnButtonService;

	private IInventoryDao inventoryDao;
	
	private QuotationService quotationService;
	
	private IPartnerDao partnerDao;

	private IReceivableDao receivableDao;
	/**
	 * 查询销售单
	 * @param queryParam
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Sale getSaleByConditions(String queryParam){
		JSONObject queryObject = JSONObject.fromObject(queryParam);
	    Map<String,Object> queryMap = (Map<String,Object>) JSONObject.toBean(queryObject,Map.class);
	    SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
	    queryMap.put("companyId", sessionMessage.getCompanyId());
	    List<Sale> sales = saleDao.getSaleByConditions(queryMap);
	    return sales.size() > 0 ? sales.get(0) : null;
	}
	
	/**
	 * 查询销售单名细
	 * 
	 * @param queryMap
	 * @return
	 */
	public List<Map<String,Object>> getSaleItem(Map<String, Object> queryMap) {

		return saleItemDao.getSaleItemForMap(queryMap);
	}

	/**
	 * 通过销售单id查询急件主表
	 * @param saleId
	 * @return Express
	 */
	public List<Express> getExpressBySaleId(Integer saleId) {

		return expressDao.getExpressBySaleId(saleId);
	}

	/**
	 * 查询急件单明细
	 * 
	 * @param queryMap
	 * @return
	 */
	public List<Map<String, Object>> getExpressItemForMapByExpressIds(List<Integer> ids) {		

		return expressItemDao.getExpressItemForMapByExpressIds(ids);
	}
	
	/**
	 * 根据销售单id查询出相关的急件id集合
	 * @param saleId
	 * @return
	 */
	public List<Integer> getExpressIdsBySaleId(Integer saleId) {
		return expressDao.getExpressIdsBySaleId(saleId);
		
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> backupCreate(String queryParam) {
		final JSONObject saleReturnAndItemsObj = JSONObject.fromObject(queryParam);
		final SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Map<String,Object> resultMap =  (Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {
				
			public Object doInTransaction(TransactionStatus status) {
				//主表
				SaleReturn saleReturn = generateSaleReturn(saleReturnAndItemsObj);
				Map<String,Object> saleReturnItems = generateSaleReturnItem(saleReturnAndItemsObj,sessionMessage);
				//删除明细
				List<Integer> deleteItemIds = generateDeleteItemIds(saleReturnAndItemsObj);
				//新增明细
				List<SaleReturnItem> addItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.ADDITEMS.getType());
				//修改明细
				List<SaleReturnItem> modifyItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.MODIFYITEMS.getType());
				//总金额
				BigDecimal totalAmount = (BigDecimal) saleReturnItems.get(ConstantParamEnum.TOTALAMOUNT.getType());
				saleReturn.setStatus(SaleReturn.STATUS_CREATE);
				saleReturn.setAmount(totalAmount);
				
				Map<String,Object> response = new HashMap<String, Object>();				
				response = handleSaleReturnAndItems(sessionMessage, saleReturn,deleteItemIds, addItems, modifyItems,false);
				if(response != null){
					return response;
				}
				//页面返回信息
				response = generateResponse(sessionMessage,saleReturn);				
				return response;
			}
		});
		
		return resultMap;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> backupSubmit(String queryParam) {
		final JSONObject saleReturnAndItemsObj = JSONObject.fromObject(queryParam);
		final SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Map<String,Object> resultMap =  (Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {
			
			@Override
			public Object doInTransaction(TransactionStatus status) {
				//主表
				SaleReturn saleReturn = generateSaleReturn(saleReturnAndItemsObj);
				Map<String,Object> saleReturnItems = generateSaleReturnItem(saleReturnAndItemsObj,sessionMessage);
				//删除明细
				List<Integer> deleteItemIds = generateDeleteItemIds(saleReturnAndItemsObj);
				//新增明细
				List<SaleReturnItem> addItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.ADDITEMS.getType());
				//修改明细
				List<SaleReturnItem> modifyItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.MODIFYITEMS.getType());
				//总金额
				BigDecimal totalAmount = (BigDecimal) saleReturnItems.get(ConstantParamEnum.TOTALAMOUNT.getType());
				saleReturn.setAmount(totalAmount);
				saleReturn.setStatus(SaleReturn.STATUS_SUBMIT);
				saleReturn.setSubmitter(sessionMessage.getUserId());
				Map<String,Object> response = new HashMap<String, Object>();
				response = handleSaleReturnAndItems(sessionMessage, saleReturn,deleteItemIds, addItems, modifyItems,false);
				if(response != null){
					return response;
				}
				//页面返回信息
				response = generateResponse(sessionMessage,saleReturn);				
				return response;
			}
		});
		return resultMap;
	}

	
	@SuppressWarnings("unchecked")
	public Map<String, Object> backupDelivery(String queryParam) {
		final JSONObject saleReturnAndItemsObj = JSONObject.fromObject(queryParam);
		final SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Map<String,Object> resultMap =  (Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {
			
			@Override
			public Object doInTransaction(TransactionStatus status) {
				SaleReturn saleReturn = generateSaleReturn(saleReturnAndItemsObj);
				Map<String,Object> saleReturnItems = generateSaleReturnItem(saleReturnAndItemsObj,sessionMessage);
				//删除明细
				List<Integer> deleteItemIds = generateDeleteItemIds(saleReturnAndItemsObj);
				//新增明细
				List<SaleReturnItem> addItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.ADDITEMS.getType());
				//修改明细
				List<SaleReturnItem> modifyItems = (List<SaleReturnItem>) saleReturnItems.get(ConstantParamEnum.MODIFYITEMS.getType());
				//总金额
				BigDecimal totalAmount = (BigDecimal) saleReturnItems.get(ConstantParamEnum.TOTALAMOUNT.getType());
				saleReturn.setAmount(totalAmount);				
				Map<String,Object> response = new HashMap<String, Object>();
				response = handleSaleReturnAndItems(sessionMessage, saleReturn,deleteItemIds, addItems, modifyItems,true);
				if(response != null){
					return response;
				}
				//更新库存表
				List<Inventory> inventories = (List<Inventory>) saleReturnItems.get(ConstantParamEnum.INVENTORIES.getType());
				
				inventoryDao.batchUpdateInventory(inventories);
				
				quotationService.handlePartPropertyAndQuotationForReturn(inventories, true);
				// 客户表里更新客户的应收款 ，应收款=原应收款-退货金额
				Partner partner = (Partner) partnerDao.getById(saleReturn.getPartnerIdBySeller());
				BigDecimal unreceived = partner.getUnreceived();
				if(unreceived == null){
					unreceived = new BigDecimal(0);
				}
				partner.setUnreceived(unreceived.subtract(saleReturn.getAmount()));
				partnerDao.updatePartnerAmountById(partner);
				// 生成应收款记录
				Receivable receivable = createReceiveable(sessionMessage,saleReturn);
				//页面返回信息
				response = generateResponse(sessionMessage,saleReturn);				
				response.put(ConstantParamEnum.RECEIVABLEID.getType(), receivable.getId());
				response.put(ConstantParamEnum.CUSTOMERID.getType(), receivable.getCustomerId());
				return response;
			}			
		});
		return resultMap;
		
	}
	
	private Receivable createReceiveable(SessionMessage sessionMessage,SaleReturn saleReturn) {
		
		Receivable receivable = new Receivable();
		Integer companyId = sessionMessage.getCompanyId();
		String code = codeGenericDao.getNewCode(companyId, CodeGeneric.RECEIVABLE);
		receivable.setCompanyId(companyId);
		receivable.setCustomerId(saleReturn.getPartnerIdBySeller());
		receivable.setCode(code);
		receivable.setDocumentType(Inventory.DDOCUMENT_TYPE_RETURNED);
		receivable.setDocumentId(saleReturn.getId());
		receivable.setDocumentCode(saleReturn.getCodeOfSeller());
		receivable.setReceivable(saleReturn.getAmount());
		receivable.setReceived(new BigDecimal(0));
		receivable.setStatus(Receivable.STATUS_UNCOMPLETE);
		receivable.setCurrentorId(sessionMessage.getUserId());
		receivableDao.create(receivable);
		return receivable;
	}	
	
	private Map<String, Object> handleSaleReturnAndItems(SessionMessage sessionMessage,SaleReturn saleReturn, 
	         List<Integer> deleteItemIds,List<SaleReturnItem> addItems, List<SaleReturnItem> modifyItems,boolean last) {
		if(saleReturn.getId() == null){
			//初次保存
			insertSaleReturn(sessionMessage, saleReturn,last);
		}else{
			//更新
			Map<String, Object> response = checkCurrentorBeforeUpdate(sessionMessage,saleReturn);
			if(response != null){
				return response;
			}
			if(last){
				saleReturn.setStatus(SaleReturn.STATUS_DELIVERY);
				saleReturn.setDeliveryerId(sessionMessage.getUserId());
				if(saleReturn.getSubmitter() == null){
					saleReturn.setSubmitter(sessionMessage.getUserId());
				}
				saleReturn.setCurrentorId(null);
			}
			getDao().update(saleReturn);
			if(deleteItemIds !=null && deleteItemIds.size() > 0){
				batchDeleteItems(deleteItemIds,saleReturn);
			}
			if(modifyItems != null && modifyItems.size() > 0){
				saleReturnItemDao.batchUpdateItems(modifyItems);
			}
		}
		if(addItems != null && addItems.size() > 0){
			addItems = setAddItemsSaleReturnId(addItems,saleReturn);
			saleReturnItemDao.batchInsertItems(addItems);
		}
		return null;
	}
	
	/**
	 * 页面返回按钮，主表，明细
	 * @param sessionMessage
	 * @param saleReturn
	 * @return
	 */
	private Map<String,Object> generateResponse(SessionMessage sessionMessage,SaleReturn saleReturn) {
		//获得按钮条
		Map<String,Object> buttons = saleReturnButtonService.generateButtonsByStatus(saleReturn.getStatus(), saleReturn.getCurrentorId(), sessionMessage.getUserId());
		//主表
		Map<String,Object> queryMap = new HashMap<String, Object>();
		queryMap.put(ConstantParamEnum.ID.getType(), saleReturn.getId());
		queryMap.put(ConstantParamEnum.VARGROUP.getType(), DictionaryEnum.GROUP_SALE_RETURN_STATUS.getGroup());
		Map<String,Object> saleReturnMap = getSaleReturnForMapByConditions(queryMap);
		//明细表
		List<Map<String,Object>> items = saleReturnItemDao.getSaleReturnItemsForMapBySaleReturnId(saleReturn.getId());
		Map<String,Object> response = new HashMap<String, Object>();
		response.put(ConstantParamEnum.BUTTONS.getType(), buttons);
		response.put(ConstantParamEnum.MAIN.getType(), saleReturnMap);
		response.put(ConstantParamEnum.DETAILS.getType(), items);
		return response;
		
	}
    /**
     * 返回Map形式的saleReturn
     * @param queryMap
     * @return
     */
	private Map<String,Object> getSaleReturnForMapByConditions(Map<String, Object> queryMap) {
		List<Map<String,Object>> saleReturnList = getDao().getSaleReturnForMapByConditions(queryMap);
		Map<String,Object> saleReturnMap = saleReturnList.size()>0 ? saleReturnList.get(0):null;
		return saleReturnMap;		
	}
	/**
	 * 设置新增明细的saleReturnId
	 * @param addItems
	 * @param saleReturn
	 * @return
	 */
	private List<SaleReturnItem> setAddItemsSaleReturnId(List<SaleReturnItem> addItems,SaleReturn saleReturn) {
		List<SaleReturnItem> saleReturnItems = new ArrayList<SaleReturnItem>();
		for(SaleReturnItem saleReturnItem : addItems){
			saleReturnItem.setSaleReturnId(saleReturn.getId());
			saleReturnItems.add(saleReturnItem);
		}
		return saleReturnItems;
		
	}
    /**
     * 批量删除记录
     * @param deleteItemIds
     * @param saleReturn
     */
	private void batchDeleteItems(List<Integer> deleteItemIds,SaleReturn saleReturn) {
		Map<String, Object> map =new HashMap<String,Object>();
		map.put(ConstantParamEnum.IDS.getType(), deleteItemIds);
		map.put(ConstantParamEnum.SALERETURNID.getType(), saleReturn.getId());
		saleReturnItemDao.batchDeleteItems(map);
	}

	/**
	 * 更新前判断单据是否是当前所有者拥有
	 * @param sessionMessage
	 * @param saleReturn
	 * @return
	 */
	private  Map<String,Object> checkCurrentorBeforeUpdate(SessionMessage sessionMessage,SaleReturn saleReturn) {
		Integer currentorId = saleReturn.getCurrentorId();
		Integer userId =sessionMessage.getUserId();
		String msg;	
		Map<String,Object> map = new HashMap<String, Object>();
		if(saleReturn.getStatus().equals(SaleReturn.STATUS_DELIVERY)&& saleReturn.getDeliveryerId()!= null){
			String deliveryName = ((User)userDao.getById(saleReturn.getDeliveryerId())).getName();
			msg = ConstantParamEnum.MSG_AHEAD.getType()+deliveryName+ConstantParamEnum.MSG_HAS_COMPLETE.getType();
			map.put(ConstantParamEnum.MSG.getType(), msg);
			map.put(ConstantParamEnum.SUCCESS.getType(), false);
			return map;
		}
		if(currentorId != null && !currentorId.equals(userId)){
			String currentorName = ((User)userDao.getById(currentorId)).getName();
			msg = ConstantParamEnum.MSG_AHEAD.getType()+currentorName+ConstantParamEnum.MSG_ISNOT_OWNER.getType();
			map.put(ConstantParamEnum.MSG.getType(), msg);
			map.put(ConstantParamEnum.SUCCESS.getType(), false);
			return map;
		}
		return null;
	}

	/**
	 * 保存主表
	 * @param sessionMessage
	 * @param saleReturn
	 */
	private void insertSaleReturn(SessionMessage sessionMessage,SaleReturn saleReturn,boolean last) {
		String codeOfSeller = codeGenericDao.getNewCode(sessionMessage.getCompanyId(), CodeGeneric.SALE_RETURN);
		saleReturn.setCodeOfSeller(codeOfSeller);
		saleReturn.setCreatorId(sessionMessage.getUserId());
		saleReturn.setCurrentorId(sessionMessage.getUserId());
		if(last){
			saleReturn.setStatus(SaleReturn.STATUS_DELIVERY);
			saleReturn.setDeliveryerId(sessionMessage.getUserId());
			if(saleReturn.getSubmitter() == null){
				saleReturn.setSubmitter(sessionMessage.getUserId());
			}
			saleReturn.setCurrentorId(null);
		}
		getDao().create(saleReturn);
	}
	/**
	 * 被删除明细主键id集合
	 * @param saleReturnAndItemsObj
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Integer> generateDeleteItemIds(JSONObject saleReturnAndItemsObj) {
	    JSONArray deleteArray = saleReturnAndItemsObj.getJSONArray(ConstantParamEnum.DELETEITEMIDS.getType());  
	    List<Integer> deleteIdList = (List<Integer>) JSONArray.toCollection(deleteArray, Integer.class);
	    return deleteIdList;
	}
	
    /**
     * 解析明细表,取得新增明细、修改明细、总退货金额
     * @param saleReturnAndItemsObj
     * @return
     */
	@SuppressWarnings("unchecked")
	private Map<String,Object> generateSaleReturnItem(JSONObject saleReturnAndItemsObj,SessionMessage sessionMessage) {
    	//明细
		JSONArray itemArray = saleReturnAndItemsObj.getJSONArray(ConstantParamEnum.DETAILS.getType());		
		//新增明细
		List<SaleReturnItem> addItems = new ArrayList<SaleReturnItem>();
		//修改明细
		List<SaleReturnItem> modifyItems = new ArrayList<SaleReturnItem>();		
		//总退货成本
		BigDecimal totalAmount = new BigDecimal(0);
		//库存
		List<Inventory> inventories = new ArrayList<Inventory>();
		List<SaleReturnItem> saleReturnItems = (List<SaleReturnItem>) JSONArray.toCollection(itemArray, SaleReturnItem.class);
		for(SaleReturnItem saleReturnItem : saleReturnItems){					
			//库存信息
			Inventory inventory = (Inventory) inventoryDao.getInventoryByIdAndCompanyId(saleReturnItem.getSourceInventoryId(),sessionMessage.getCompanyId(),true);			
			if(!inventory.getOnHand().equals(0)){
				saleReturnItem.setStoreId(inventory.getStoreId());
			}
			Integer onHand = inventory.getOnHand()+saleReturnItem.getQuantity();
			inventory.setOnHand(onHand);
			inventory.setChangeQuantity(saleReturnItem.getQuantity());
			inventories.add(inventory);
			
			BigDecimal retailAmount = saleReturnItem.getRetailPrice().multiply(new BigDecimal(saleReturnItem.getQuantity()));
			
			saleReturnItem.setRetailAmount(retailAmount);
			saleReturnItem.setCost(inventory.getCost());
			totalAmount = totalAmount.add(retailAmount);
			if(saleReturnItem.getId() == null){
				//新增明细				
				addItems.add(saleReturnItem);						
			}else{
				//修改明细
				modifyItems.add(saleReturnItem);
			}
			
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put(ConstantParamEnum.ADDITEMS.getType(), addItems);
		map.put(ConstantParamEnum.MODIFYITEMS.getType(),modifyItems);
		map.put(ConstantParamEnum.TOTALAMOUNT.getType(),totalAmount);
		map.put(ConstantParamEnum.INVENTORIES.getType(), inventories);
		return map;
	}

	/**
     * 解析出主表
     * @param saleReturnAndItemsObj
     * @return saleReturn
     */
	private SaleReturn generateSaleReturn(JSONObject saleReturnAndItemsObj) {
		SessionMessage sessionMessage =UserHolder.getCurrentSessionMessage();
		JSONObject saleReturnObj = saleReturnAndItemsObj.getJSONObject(ConstantParamEnum.MAIN.getType());
		SaleReturn saleReturn = (SaleReturn) JSONObject.toBean(saleReturnObj, SaleReturn.class);
		if(saleReturn.getId() == null){
			saleReturn.setSellerId(sessionMessage.getCompanyId());
		}else{
			SaleReturn saleReturn2 = getSaleReturnByIdAndSellerId(saleReturn.getId(),sessionMessage.getCompanyId(),false);
			BeanUtils.copyProperties(saleReturn2, saleReturn, new String[]{"buyerId","partnerIdBySeller","memoOfSeller","gmtRealDelivery"});
		}
		return saleReturn;
	}
    /**
     * 根据id查询saleReturn
     * @param id
     * @param companyId
     * @param update，是否用于更新操作
     * @return
     */
	private SaleReturn getSaleReturnByIdAndSellerId(Integer id,Integer companyId, boolean update) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put(ConstantParamEnum.ID.getType(), id);
		map.put(ConstantParamEnum.SELLERID.getType(), companyId);
		map.put(ConstantParamEnum.UPDATE.getType(), update);
		SaleReturn saleReturn = getDao().getSaleReturnById(map);
		return saleReturn;
	}
	/**
	 * 销售退货浏览
	 * @param queryMap
	 * @param saleReturnListModel
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public ListModel getSaleReturnListModelByConditions(Map<String, Object> queryMap, ListModel saleReturnListModel) {
		queryMap.put(ConstantParamEnum.VARGROUP.getType(), DictionaryEnum.GROUP_SALE_STATUS.getGroup());
		queryMap.put(ConstantParamEnum.COMPANYID.getType(), UserHolder.getCurrentSessionMessage().getCompanyId());
		saleReturnListModel.setTotal(getDao().getSaleReturnCountByConditions(queryMap));
		if(saleReturnListModel.getOrderBy() == null){
			saleReturnListModel.setOrderBy(ConstantParamEnum.ORDERBY_GMTREALDELIVERY.getType());
		}
		queryMap.put(ConstantParamEnum.LISTMODEL.getType(), saleReturnListModel);
		List<Map<String, Object>> saleReturns = getDao().getSaleReturnForMapByConditions(queryMap);
		saleReturnListModel.setResult(saleReturns);
		return saleReturnListModel;
		
	}
	
	@SuppressWarnings("unchecked")
	public ListModel getSaleReturnItemListModelByConditions(Map<String, Object> queryMap, ListModel saleReturnItemListModel) {
		 SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		 queryMap.put(ConstantParamEnum.COMPANYID.getType(), sessionMessage.getCompanyId());
		 saleReturnItemListModel.setTotal(saleReturnItemDao.getSaleReturnItemCountByConditions(queryMap));
		 if(saleReturnItemListModel.getOrderBy() == null){
			 saleReturnItemListModel.setOrderBy(SaleConstantEnum.CODEOFSELLER.getType());
		 }
		 queryMap.put(SaleConstantEnum.LISTMODEL.getType(), saleReturnItemListModel);
		 List<Map> result =  saleReturnItemDao.getSaleReturnItemForMapByConditions(queryMap);
		 saleReturnItemListModel.setResult(result);
		 return saleReturnItemListModel;
	}
    /**
     * 根据id查询主表，明细，及获得按钮
     * @param saleReturnId
     * @return
     */
	public Map<String,Object> getSaleReturnAndItemById(Integer saleReturnId) {
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		SaleReturn saleReturn = getSaleReturnByIdAndSellerId(saleReturnId,sessionMessage.getCompanyId(), false);
		Map<String,Object> response = generateResponse(sessionMessage, saleReturn);
		return response;
	}
	/**
	 * 接手或释放单据后加载新的按钮
	 * @param id
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> updateSaleReturnCurrentorId(final Integer id ,final Integer userId) {
		final SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Map<String, Object> result = (Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {
			
			@Override
			public Object doInTransaction(TransactionStatus status) {
				SaleReturn saleReturn = getSaleReturnByIdAndSellerId(id, sessionMessage.getCompanyId(), true);
				saleReturn.setCurrentorId(userId);
				getDao().update(saleReturn);
				Map<String, Object> buttons =saleReturnButtonService.generateButtonsByStatus(saleReturn.getStatus(), saleReturn.getCreatorId(), sessionMessage.getUserId());
			    buttons.put(ConstantParamEnum.SUCCESS.getType(), true);
			    return buttons;
			}
		});
		return result;
	}
	/**
	 * 根据条件删除saleReturn
	 * @param id
	 * @return
	 */
	public Map<String,Object> deleteSaleReturnById(Integer id) {
		SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		SaleReturn saleReturn = getSaleReturnByIdAndSellerId(id,sessionMessage.getCompanyId(), false);
		Map<String,Object> response = checkCurrentorBeforeUpdate(sessionMessage, saleReturn);
		if(response != null){
			return response;
		}
		Map<String,Object> map = new HashMap<String, Object>(); 
		map.put(ConstantParamEnum.ID.getType(), id);
		map.put(ConstantParamEnum.SELLERID.getType(), sessionMessage.getCompanyId());
		boolean success = getDao().deleteById(map);
		map.clear();
		if(success){
			map.put(ConstantParamEnum.SUCCESS.getType(), true);
			map.put(ConstantParamEnum.MSG.getType(), ConstantParamEnum.DELETE_DRAFT_SUCCESS.getType());
		}else{
			map.put(ConstantParamEnum.SUCCESS.getType(), false);
			map.put(ConstantParamEnum.MSG.getType(), ConstantParamEnum.DRAFT_NOT_EXIST.getType());
		}
		return map;
	}
	/**
	 * 待仓库审核状态退回草稿状态
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> updateSaleReturnStatusById(final Integer id) {
		final SessionMessage sessionMessage = UserHolder.getCurrentSessionMessage();
		Map<String, Object> result = (Map<String, Object>) transactionTemplate.execute(new TransactionCallback() {			
			@Override
			public Object doInTransaction(TransactionStatus status) {
			     SaleReturn saleReturn = getSaleReturnByIdAndSellerId(id, sessionMessage.getCompanyId(), true);	
			     Map<String,Object> response = checkCurrentorBeforeUpdate(sessionMessage, saleReturn);
			     if(response != null){
					return response;
			     }
			     saleReturn.setStatus(SaleReturn.STATUS_CREATE);
			     saleReturn.setSubmitter(null);
			     saleReturn.setGmtSubmit(null);
			     getDao().update(saleReturn);
			     Map<String,Object> resp = getSaleReturnAndItemById(id);
			     resp.put(ConstantParamEnum.SUCCESS.getType(), true);
			     resp.put(ConstantParamEnum.MSG.getType(), ConstantParamEnum.BACK_TO_DRAFT_SUCCESS.getType());
			     return resp;
			}
		});
		return result;
	}

	
	
	public void setSaleItemDao(ISaleItemDao saleItemDao) {
		this.saleItemDao = saleItemDao;
	}

	public void setExpressDao(IExpressDao expressDao) {
		this.expressDao = expressDao;
	}

	public void setExpressItemDao(IExpressItemDao expressItemDao) {
		this.expressItemDao = expressItemDao;
	}

	public void setSaleDao(ISaleDao saleDao) {
		this.saleDao = saleDao;
	}

	public void setCodeGenericDao(ICodeGenericDao codeGenericDao) {
		this.codeGenericDao = codeGenericDao;
	}

	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	public void setSaleReturnItemDao(ISaleReturnItemDao saleReturnItemDao) {
		this.saleReturnItemDao = saleReturnItemDao;
	}

	public void setSaleReturnButtonService(
			SaleReturnButtonService saleReturnButtonService) {
		this.saleReturnButtonService = saleReturnButtonService;
	}

	public void setInventoryDao(IInventoryDao inventoryDao) {
		this.inventoryDao = inventoryDao;
	}
	
	public void setPartnerDao(IPartnerDao partnerDao) {
		this.partnerDao = partnerDao;
	}

	public void setReceivableDao(IReceivableDao receivableDao) {
		this.receivableDao = receivableDao;
	}

	public void setQuotationService(QuotationService quotationService) {
		this.quotationService = quotationService;
	}


}
